type WinSizeType = "lg" | "md" | "sm" | "xs" | "xxs";
interface IntervalCheckOptions {
    checker: () => boolean;
    onSuc: () => void;
    period?: number;
}
interface LazyCheckOptions {
    prev: string | HTMLElement | JQuery;
    next: string | HTMLElement | JQuery;
    onSuc: () => void;
}
const rootDom = document.body;
(function () {
    // @ts-ignore
    if (!window.gloablVAR) {
        // @ts-ignore
        window.gloablVAR = {}
    }
    var elements = document.querySelectorAll('.sticky-box');
    window.Stickyfill.add(elements);
    gsap.registerPlugin(ScrollTrigger);
    // lg >1920
    // md 1440 < md <= 1920
    // 1000 < sm <= 1440
    // 768 < xs <= 1000
    // xxs <=768
    const winSize = $(rootDom).width();
    let winSizeType: WinSizeType = 'md';
    if (winSize > 1920) {
        winSizeType = 'lg';
    } else if (winSize > 1440 && winSize <= 1920) {
        winSizeType = 'md';
    } else if (winSize > 1000 && winSize <= 1440) {
        winSizeType = 'sm';
    } else if (winSize > 768 && winSize <= 1000) {
        winSizeType = 'xs';
    } else if (winSize <= 768) {
        winSizeType = 'xxs';
    }
    winSizeType = 'md';

    /**
     * 通用函数，通过定时器检查是否满足条件
     * @param options 
     */
    const intervalCheck = (options: IntervalCheckOptions) => {
        const { checker, onSuc, period } = options;

        var timer = setInterval(function () {
            const isHit = checker();
            if (isHit) {
                clearInterval(timer);
                onSuc();
            }
        }, period || 300);
    }

    /**
     * 通用函数，检查是否满足懒加载条件：
     * 进入前一个元素之后，到达后一个元素之前
     * @param options 
     */
    const lazyCheck = (options: LazyCheckOptions) => {
        const { prev, next } = options;
        intervalCheck({
            checker: () => {
                const $prev = $(prev)
                const $next = $(next)
                // 进入前一个之后，到达后一个元素之前
                return $(rootDom).scrollTop() >= $prev.offset().top && $(rootDom).scrollTop() <= $next.offset().top;
            },
            onSuc: options.onSuc,
            period: 300,
        })
    }

    // 1.首页banner，无需代码

    // 2.观看影片
    (function () {
        const $movie = $('.tws-movie');
        const $picture = $movie.find(".video");
        const $btnPlay = $movie.find(".btn-play");
        lazyCheck({
            prev: '.tws-kv',
            // todo: next需要替换成真实的后一个元素
            next: '.tws-breath',
            onSuc: () => {
                $btnPlay.prepend
                $picture.prepend(`
                <video autoplay="autoplay" loop="loop" muted="true" playsinline="true" webkit-playsinline="true">
                <source src="https://www.oppo.com/content/dam/oppo/product-asset-library/find-x3-series/fussi-mars/v1/assets/pc-cfc300.mp4" type="video/mp4">
              </video>
                `)
            }
        });
        $btnPlay.click(function (e) {
            new window.Video({
                mount: '#J_video',
                // todo: 这里的mp4需要替换
                url: "https://www.sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4",
                // post: $btnPlay.data("poster"),
                closeCallBack: () => {
                    console.log("close video modal")
                }
            })
        });
        $movie.mouseenter(function () {
            $btnPlay.css("z-index", "unset")
        })
        $movie.mouseleave(function () {
            $btnPlay.css("z-index", '-1')
        })
        const width = $btnPlay.width();
        $movie.mousemove(function (e) {
            // const movieY = $(document.body).scrollTop() + $movie.offset().top
            // console.log(`
            //     clientY: ${e.clientY},
            //     offsetY: ${e.offsetY},
            //     pageY:${e.pageY},
            //     movieY: ${movieY},
            //     screenY: ${e.screenY}
            // `)
            $btnPlay.css("left", e.pageX - width / 2);
            $btnPlay.css("top", e.pageY - $movie.offset().top - width / 2);
        })
    })();

    // 3.亮点
    (function () {
        const $sale = $('.tws-sale');
        const $sale1 = $sale.find('.sale1');
        const $sale2 = $sale.find('.sale2');
        const $sale3 = $sale.find('.sale3');
        const $sale4 = $sale.find('.sale4');
        const $sale5 = $sale.find('.sale5');
        const $sale6 = $sale.find('.sale6');

        const gt = gsap.timeline();
        const duration = 1;
        gt.from($sale1, {
            scale: 0.3,
            opacity: 0,
            duration,
        }).from($sale2, {
            scale: 0.3,
            opacity: 0,
            duration: 0.7,
        }, `-=${duration}`).from($sale3, {
            scale: 0.3,
            opacity: 0,
            duration,
        }, `-=${duration}`).from($sale4, {
            scale: 0.3,
            opacity: 0,
            duration,
        }, `-=${duration}`).from($sale5, {
            scale: 0.3,
            opacity: 0,
            duration,
        }, `-=${duration}`).from($sale6, {
            scale: 0.3,
            opacity: 0,
            duration,
        }, `-=${duration}`);
        ScrollTrigger.create({
            animation: gt,
            trigger: $sale,
            toggleActions: "restart none none none",
            start: 'top 50%',
            end: "bottom bottom",
        });
    })();

    // 4.耳机拆解
    (function () {
        const $yinxiao = $('.tws-yinxiao');
        const $chaijie = $('.tws-chaijie');
        const $chaijieCanvas = $chaijie.find(".tws-chaijie-animate")
        const chaijieCanvas = $chaijieCanvas.get(0) as HTMLCanvasElement;
        const chaijieCanvasCtx = chaijieCanvas.getContext('2d');
        const chaijieCanvasSizeDic: Record<WinSizeType, { width: number; height: number }> = {
            "lg": {
                width: 1116,
                height: 774,
            },
            "md": {
                width: 1240,
                height: 860,
            },
            "sm": {
                width: 744,
                height: 516,
            },
            "xs": {
                width: 434,
                height: 301,
            },
            "xxs": {
                width: 434,
                height: 301,
            }
        }
        let chaijieCanvasSize = chaijieCanvasSizeDic[winSizeType];
        if (['xs', 'xxs'].indexOf(winSizeType) >= 0) {
            chaijieCanvas.width = 4 * chaijieCanvasSize.width;
            chaijieCanvas.height = 4 * chaijieCanvasSize.height;
            chaijieCanvasCtx.scale(4, 4)
        } else {
            chaijieCanvas.width = 2 * chaijieCanvasSize.width;
            chaijieCanvas.height = 2 * chaijieCanvasSize.height;
            chaijieCanvasCtx.scale(2, 2)
        }
        chaijieCanvasCtx.clearRect(0, 0, chaijieCanvasSize.width, chaijieCanvasSize.height);

        // 因为图片较大，所以原来是分为了2个尺寸
        // 初次滚动到耳机时，预加载图片
        // todo: 这里需要替换文件夹
        const IMAGE_HOST = 'https://wwwstatic.vivo.com.cn/vivoportal/files/resource/product/1624072018921/images/';
        const imgArr = [];
        lazyCheck({
            prev: '.tws-sale',
            next: '.tws-breath',
            onSuc: () => {
                for (let imgIndex = 0; imgIndex <= 69; imgIndex++) {
                    imgArr[imgIndex] = new Image();
                    imgArr[imgIndex].src = IMAGE_HOST + "tws2-dream-lg_" + imgIndex + ".jpg";
                }
                $chaijieCanvas.css('background-image', `url(${IMAGE_HOST}tws2-dream-lg_0.jpg)`);
            }
        })
        // 动画变量，从0到69
        const aniVar = {
            curImg: 0,
        };

        const gtFull = gsap.timeline();
        gtFull.from($yinxiao, {
            duration: 1,
            autoAlpha: 0,
            yPercent: 100,
        }).from($chaijieCanvas, {
            duration: 2,
            autoAlpha: 0,
            yPercent: 80,
        }, "-=1").to($yinxiao, {
            duration: 1,
            autoAlpha: 0,
            yPercent: -80
        }, "-=1").to(aniVar, {
            duration: 1,
            curImg: 69,
            roundProps: "curImg",
            onUpdate: function () {
                if (imgArr.length <= 0) {
                    return;
                }
                chaijieCanvasCtx.clearRect(0, 0, chaijieCanvasSize.width, chaijieCanvasSize.height);
                chaijieCanvasCtx.drawImage(imgArr[aniVar.curImg], 0, 0, chaijieCanvasSize.width, chaijieCanvasSize.height);
            },
            ease: "linear",
        }, "-=1");
        // .from($line1, .5, {
        //     autoAlpha: 0,
        //     height: 0
        // }).from($line2, .5, {
        //     autoAlpha: 0,
        //     height: 0
        // },"-=.5").from($txt, .5, {
        //     autoAlpha: 0
        // });
        ScrollTrigger.create({
            animation: gtFull,
            trigger: $chaijie,
            start: "top center",
            end: "bottom bottom",
            scrub: true,
            anticipatePin: 1,
            markers: false,
        });

        // const gtCanvas = gsap.timeline();
        // gtCanvas.to(aniVar, {
        //     duration: 1,
        //     curImg: 69,
        //     roundProps: "curImg",
        //     onUpdate: function () {
        //         if (imgArr.length <= 0) {
        //             return;
        //         }
        //         chaijieCanvasCtx.clearRect(0, 0, chaijieCanvasSize.width, chaijieCanvasSize.height);
        //         chaijieCanvasCtx.drawImage(imgArr[aniVar.curImg], 0, 0, chaijieCanvasSize.width, chaijieCanvasSize.height);
        //     },
        //     ease: "linear",
        // });
        // ScrollTrigger.create({
        //     animation: gtCanvas,
        //     trigger: $chaijie,
        //     scrub: true,
        //     start: `top top`,
        //     end: "bottom bottom",
        //     markers: false
        // });
    })();

    // 5.气体流通
    (function () {
        const $breath = $('.tws-breath');
        const $titleWrapper = $breath.find(".title-wrapper");
        const $breathBox = $breath.find('.tws-breath-animate-box');
        const $breathCanvas = $breath.find('.tws-breath-animate');
        const breathCanvas = $breath.find('.tws-breath-animate').get(0) as HTMLCanvasElement;
        const breathCanvasCtx = breathCanvas.getContext('2d');

        const breathCanvasSizeDic: Record<WinSizeType, { width: number; height: number }> = {
            "lg": {
                width: 1200,
                height: 600,
            },
            "md": {
                width: 900,
                height: 450,
            },
            "sm": {
                width: 600,
                height: 300,
            },
            "xs": {
                width: 420,
                height: 210,
            },
            "xxs": {
                width: 420,
                height: 210,
            }
        };
        let breathCanvasSize = breathCanvasSizeDic[winSizeType];
        if (['xs', 'xxs'].indexOf(winSizeType) >= 0) {
            breathCanvas.width = 4 * breathCanvasSize.width;
            breathCanvas.height = 4 * breathCanvasSize.height;
            breathCanvasCtx.scale(4, 4)
        } else {
            breathCanvas.width = 2 * breathCanvasSize.width;
            breathCanvas.height = 2 * breathCanvasSize.height;
            breathCanvasCtx.scale(2, 2)
        }
        breathCanvasCtx.clearRect(0, 0, breathCanvasSize.width, breathCanvasSize.height);

        // 图片统一用1200*600
        // 初次滚动到耳机时，预加载图片
        // todo: 这里需要替换文件夹
        const IMAGE_HOST = 'https://wwwstatic.vivo.com.cn/vivoportal/files/resource/product/1624072018921/images/';
        const imgArr = [];
        lazyCheck({
            // todo: prev和next需要替换
            prev: '.tws-kv',
            next: '.tws-swiper',
            onSuc: () => {
                for (let imgIndex = 0; imgIndex <= 126; imgIndex++) {
                    imgArr[imgIndex] = new Image();
                    imgArr[imgIndex].src = IMAGE_HOST + "tws2-breath-lg_" + imgIndex + ".jpg";
                }
                $breathCanvas.css('background-image', `url(${IMAGE_HOST}tws2-breath-lg_0.jpg)`);
            }
        })
        // 动画变量，从0到126
        const aniVar = {
            curImg: 0,
        };
        const gtCanvas = gsap.timeline();
        gtCanvas.to(aniVar, {
            duration: 1,
            curImg: 126,
            roundProps: "curImg",
            onUpdate: function () {
                if (imgArr.length <= 0) {
                    return;
                }
                breathCanvasCtx.clearRect(0, 0, breathCanvasSize.width, breathCanvasSize.height);
                breathCanvasCtx.drawImage(imgArr[aniVar.curImg], 0, 0, breathCanvasSize.width, breathCanvasSize.height);
            },
            ease: "linear",
        });
        ScrollTrigger.create({
            animation: gtCanvas,
            trigger: $breath,
            scrub: true,
            start: `top top`,
            end: "bottom bottom",
            markers: false
        });

        const gtBox = gsap.timeline();
        gtBox.from($titleWrapper, {
            duration: 1,
            autoAlpha: 0,
            y: 200,
            ease: Power1.easeInOut
        }).from($breathBox, {
            duration: 1,
            autoAlpha: 0,
            y: 200,
            ease: Power1.easeInOut
        }, "-=1");
        ScrollTrigger.create({
            animation: gtBox,
            trigger: $breath,
            scrub: true,
            start: "top center",
            end: "top 20%",
        });

        // const gtFull = gsap.timeline();
        // gtFull.from($titleWrapper, {
        //     duration: 1,
        //     autoAlpha: 0,
        //     yPercent: 100,
        // }).from($breathBox, {
        //     duration: 2,
        //     autoAlpha: 0,
        //     yPercent: 80,
        // }, "-=1").to($titleWrapper, {
        //     duration: 1,
        //     autoAlpha: 0,
        //     yPercent: -80
        // }, "-=1").to(aniVar, {
        //     duration: 1,
        //     curImg: 126,
        //     roundProps: "curImg",
        //     onUpdate: function () {
        //         if (imgArr.length <= 0) {
        //             return;
        //         }
        //         breathCanvasCtx.clearRect(0, 0, breathCanvasSize.width, breathCanvasSize.height);
        //         breathCanvasCtx.drawImage(imgArr[aniVar.curImg], 0, 0, breathCanvasSize.width, breathCanvasSize.height);
        //     },
        //     ease: "linear",
        // });
        // ScrollTrigger.create({
        //     animation: gtFull,
        //     trigger: $breath,
        //     start: "top center",
        //     end: "bottom bottom",
        //     scrub: true,
        //     anticipatePin: 1,
        //     markers: true,
        // });
    })();

    // 6.音效tab+跑马灯
    (function () {
        // @ts-ignore
        const swiper = new Swiper('.swiper', {
            slidesPerView: 'auto',
            spaceBetween: 50,
            centeredSlides: true,
            loop: true,
        });
        swiper.slideTo(1);
        $('.js-item1').click(function () {
            $('.js-item1 .s-tit').addClass('active')
            $('.js-item2 .s-tit').removeClass('active')
            $('.js-item3 .s-tit').removeClass('active')
            swiper.slideTo(0);
        })
        $('.js-item2').click(function () {
            $('.js-item1 .s-tit').removeClass('active')
            $('.js-item2 .s-tit').addClass('active')
            $('.js-item3 .s-tit').removeClass('active')
            swiper.slideTo(1);
        })
        $('.js-item3').click(function () {
            $('.js-item1 .s-tit').removeClass('active')
            $('.js-item2 .s-tit').removeClass('active')
            $('.js-item3 .s-tit').addClass('active')
            swiper.slideTo(2);
        })

        const $twsSwiper = $('.tws-swiper');
        const $deepDes = $('.deep-des');
        const $tab = $('.tab');
        const $swiper = $('.swiper');
        const gt = gsap.timeline();
        // gt.from($deepDes, {
        //     duration: 1,
        //     autoAlpha: 0,
        //     y: 200,
        //     ease: Power1.easeInOut
        // }).from($tab, {
        //     duration: 1,
        //     autoAlpha: 0,
        //     y: 200,
        //     ease: Power1.easeInOut
        // }, '-=1').from($swiper, {
        //     duration: 1,
        //     autoAlpha: 0,
        //     y: 200,
        //     ease: Power1.easeInOut
        // }, '-=1');
        // ScrollTrigger.create({
        //     animation: gt,
        //     trigger: $twsSwiper,
        //     scrub: true,
        //     start: "top center",
        //     end: "bottom bottom",
        // });
    })();

    // 7.层叠动画
    (function () {
        const sections = gsap.utils.toArray(".stack-item")
        sections.forEach((stackItem, i) => {
            console.log('stackItem', stackItem)
            ScrollTrigger.create({
                trigger: stackItem as any,
                start: "top top",
                pin: true,
                snap: 1 / (sections.length - 1),
                markers: true
            });
        });
    })();

    // 8.灵动腰线
    (function () {
        const $beltline = $('.tws-beltline');
        const $beltlineCanvas = $beltline.find('.tws-beltline-animate');
        const beltlineCanvas = $beltlineCanvas.get(0) as HTMLCanvasElement;
        const beltlineCanvasCtx = beltlineCanvas.getContext('2d');
        const beltlineCanvasSizeDic: Record<WinSizeType, { width: number; height: number }> = {
            "lg": {
                width: 1920,
                height: 1080,
            },
            "md": {
                width: 1200,
                height: 800,
            },
            "sm": {
                width: 800,
                height: 500,
            },
            "xs": {
                width: 375,
                height: 200,
            },
            "xxs": {
                width: 375,
                height: 200,
            }
        }
        let beltlineCanvasSize = beltlineCanvasSizeDic[winSizeType];
        if (['xs', 'xxs'].indexOf(winSizeType) >= 0) {
            beltlineCanvas.width = 4 * beltlineCanvasSize.width;
            beltlineCanvas.height = 4 * beltlineCanvasSize.height;
            beltlineCanvasCtx.scale(4, 4)
        } else {
            beltlineCanvas.width = 2 * beltlineCanvasSize.width;
            beltlineCanvas.height = 2 * beltlineCanvasSize.height;
            beltlineCanvasCtx.scale(2, 2)
        }
        beltlineCanvasCtx.clearRect(0, 0, beltlineCanvasSize.width, beltlineCanvasSize.height);

        // 初次滚动到耳机时，预加载图片
        // todo: 这里需要替换文件夹
        const IMAGE_HOST = 'https://wwwstatic.vivo.com.cn/vivoportal/files/resource/product/1624072018921/images/';
        const imgArr = [];
        lazyCheck({
            prev: '.tws-stack',
            next: '.tws-tiger',
            onSuc: () => {
                for (let imgIndex = 0; imgIndex <= 131; imgIndex++) {
                    imgArr[imgIndex] = new Image();
                    imgArr[imgIndex].src = IMAGE_HOST + "tws2-denoise-lg_" + imgIndex + ".jpg";
                }
                $beltlineCanvas.css('background-image', `url(${IMAGE_HOST}tws2-denoise-lg_0.jpg)`);
            }
        })
        // 动画变量，从0到131
        const aniVar = {
            curImg: 0,
        };
        const gtCanvas = gsap.timeline();
        gtCanvas.to(aniVar, {
            duration: 1,
            curImg: 131,
            roundProps: "curImg",
            onUpdate: function () {
                if (imgArr.length <= 0) {
                    return;
                }
                beltlineCanvasCtx.clearRect(0, 0, beltlineCanvasSize.width, beltlineCanvasSize.height);
                beltlineCanvasCtx.drawImage(imgArr[aniVar.curImg], 0, 0, beltlineCanvasSize.width, beltlineCanvasSize.height);
            },
            ease: "linear",
        });
        ScrollTrigger.create({
            animation: gtCanvas,
            trigger: $beltline,
            scrub: true,
            start: `top top`,
            end: "bottom bottom",
            markers: false
        });
    })();

    // 9.色彩碰撞
    (function () {
        const $color = $('.tws-color');
        const $section = $color.find('.section');
        const gt = gsap.timeline();
        gt.from($section, {
            duration: 1,
            autoAlpha: 0,
            y: 200,
            ease: Power1.easeInOut
        });
        ScrollTrigger.create({
            animation: gt,
            trigger: $color,
            scrub: true,
            start: "top center",
            end: "top 20%",
        });
    })()
})();

